package com.key.puzzlemodel.puzzlephoto

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.key.puzzlemodel.R
import com.key.puzzlemodel.bean.PhotoBean
import com.key.puzzlemodel.databinding.FragmentPuzzlePhotoItemBinding
import com.key.puzzlemodel.mvvm.BaseMVVMPhotoFragment
import com.key.puzzlemodel.util.DateUtil
import com.key.puzzlemodel.util.UriUtil
import com.key.puzzlemodel.view.ManageDialog

/**
 *
 * @功能描述:     相册实现
 * @创建时间:     2021/12/31
 * @创建者:       阳
 * @修改时间:     2021/12/31
 * @修改者:       阳
 */
class PuzzlePhotoItemFragment(val photoSpanCount: Int = 3) :
    BaseMVVMPhotoFragment<FragmentPuzzlePhotoItemBinding, PuzzlePhotoItemMVVMViewModel>() {

    override val layoutId: Int
        get() = R.layout.fragment_puzzle_photo_item

    private val duration: Int = 500
    private var lastClickTime: Long = 0
    private var oldSize = 0
    private var recyclePosition = 0
    private var isMultiSelect = false
    private val mSelectMap: LinkedHashMap<Int, PhotoBean> =
        LinkedHashMap<Int, PhotoBean>()

    private val manageDialog by lazy {
        ManageDialog(requireActivity(), getString(R.string.loading))
    }

    public fun setMultiSelect(multiSelect: Boolean) {
        this.isMultiSelect = multiSelect
    }


    override fun initView(savedInstanceState: Bundle?) {
        mVDB.recyclerView.layoutManager = GridLayoutManager(requireContext(), photoSpanCount)
        mVDB.recyclerView.addItemDecoration(PhotoItemDecoration())
        mVDB.recyclerView.adapter = PhotoSelectAdapter2(mVM.photoList)


        mVDB.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (RecyclerView.SCROLL_STATE_IDLE == newState && recyclePosition == oldSize - 1 && mVM.hasPhoto) {
                    mVM.loadPhoto(requireContext())
                    if (mVM.hasPhoto) {
                        manageDialog.setIsShow(true)
                    }
                }
            }
        })

        mVM.photoLoading.observe(this, { it ->
            if (it) {
                manageDialog.setIsShow(false)
//                mVDB.recyclerView.adapter!!.notifyItemRangeInserted(oldSize, mVM.photoList.size)
                oldSize = mVM.photoList.size

                mVDB.recyclerView.adapter!!.notifyDataSetChanged()
            }
        })
    }

    override fun loadPhoto(demoList: ArrayList<PhotoBean>) {
        if (checkPermission(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE))) {
            mVM.offset = 0
            mVM.hasPhoto = true
            manageDialog.setIsShow(true)
            mVM.loadPhoto(requireContext(), demoList)
        }
    }


    inner class PhotoSelectAdapter2(
        private var mPhotoList: ArrayList<Any>,
    ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val today = DateUtil.getDateNow()// 今天日期
        private var prevDateIdx = -1
        private var nextDateIdx = -1
        private val maxPictureNums = 9


        inner class DateHolder(val view: View) : RecyclerView.ViewHolder(view) {
            val dateText: TextView = view.findViewById(R.id.date)
        }

        inner class PhotoHolder(val view: View) : RecyclerView.ViewHolder(view) {
            val photoView: ImageView = view.findViewById(R.id.photo)
            val text: TextView = view.findViewById(R.id.tv_demo)
            val checkBox: CheckBox = view.findViewById(R.id.cb_check)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (0 == viewType) {
                DateHolder(
                    LayoutInflater.from(requireContext())
                        .inflate(R.layout.puzzle_item_photo_select_date, parent, false)
                )
            } else {
                val view = LayoutInflater.from(requireContext())
                    .inflate(R.layout.puzzle_item_photo_select_grid, parent, false)
                val holder = PhotoHolder(view)

                holder
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, @SuppressLint("RecyclerView") position: Int) {
            recyclePosition = position
            if (holder is DateHolder) {
                var date = mPhotoList[position] as String
                if (date == today) {
                    holder.dateText.text = requireContext().getString(R.string.string_today)
                } else {
                    holder.dateText.text = "$date ${DateUtil.getWeekByDate(date)}"
                }
                holder.view.tag = 0// 日期文本
            } else if (holder is PhotoHolder) {
                val bean = mPhotoList[position] as PhotoBean
                holder.photoView.tag = bean
                if (bean.uri.toString().contains("android.resource:")) {
                    holder.text.visibility = View.VISIBLE
                } else {
                    holder.text.visibility = View.GONE
                }

                if (isMultiSelect) {
                    holder.checkBox.visibility = View.VISIBLE
                } else {
                    holder.checkBox.visibility = View.GONE
                }
                holder.photoView.setOnClickListener {
                    if (isMultiSelect) {
                        val path = UriUtil.getRealPath(requireContext(), bean.uri)
                        if (path != null && !pictureFormatDetection(path)) {
                            Toast.makeText(
                                requireContext(),
                                "暂不支持此格式",
                                Toast.LENGTH_SHORT
                            ).show()
                        } else {
                            holder.checkBox.isChecked = !holder.checkBox.isChecked
                        }
                    } else {
                        val currentTime = System.currentTimeMillis()
                        if (currentTime - lastClickTime > duration || currentTime - lastClickTime < 0) {
                            lastClickTime = currentTime
                            if (null != photoSelectedListener) {
                                photoSelectedListener!!.invoke(bean.uri)
                            } else {
                                Toast.makeText(
                                    requireContext(),
                                    "No select listener is set!",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }

                }

                /**
                 * 在recyclerView的列表中使用checkBox当选中后由于复用问题会导致本来没选中的也处展示的为选中解决方案
                 * 在每次设置checkbox是否选中的时候先把setOnCheckedChangeListener置为null。
                 */
                if (isMultiSelect) {
                    holder.checkBox.setOnCheckedChangeListener(null)
                    holder.checkBox.isChecked =
                        if (mSelectMap.containsKey(position)) mSelectMap[position]?.selected == true else false
                    holder.checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
                        val path = UriUtil.getRealPath(requireContext(), bean.uri)
                        if (isChecked) {
                            if (mSelectMap.size > maxPictureNums - 1) {
                                holder.checkBox.isChecked = false
                                bean.selected = false
                                Toast.makeText(
                                    context, "最多选择" + maxPictureNums
                                            + "张照片噢！", Toast.LENGTH_SHORT
                                ).show()
                            } else {
                                if (path != null && !pictureFormatDetection(path)) {
                                    holder.checkBox.isChecked = false
                                    bean.selected = false
                                    Toast.makeText(
                                        requireContext(),
                                        "暂不支持此格式",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                } else {
                                    bean.selected = true
                                    mSelectMap[position] = bean
                                    multiPhotoSelectedListener!!.invoke(mSelectMap)
                                }
                            }
                        } else {
                            mSelectMap.remove(position)
                            multiPhotoSelectedListener!!.invoke(mSelectMap)
                            bean.selected = false
                        }
                    }

                }


                Glide.with(this@PuzzlePhotoItemFragment).load(
                    if (0 < bean.imageId) {
                        bean.uri.toString()
                    } else {
                        bean.uri
                    }
                ).into(holder.photoView)


                findDateIdx(position)

                holder.view.tag = -1
//
//                val value1 = (position - prevDateIdx - 1) % photoSpanCount
//                val value2 = (nextDateIdx - position) % photoSpanCount
//                val value3 = (nextDateIdx - prevDateIdx) % photoSpanCount

                // 判断图片是否在第一列
//                if (0 == value1) {
//                    holder.view.tag = 1
//                }

                // 判断图片区是否在最后一行
//                if (3 >= nextDateIdx - position && value3 < 3) {
//
//                    holder.view.tag = 2
//
//                    if (0 == value1) {// 第一列且最后一行
//                        holder.view.tag = 3
//                    }
//                }
            }
        }


        override fun getItemCount(): Int {
            return mPhotoList.size
        }

        override fun getItemViewType(position: Int): Int {
            val value = mPhotoList[position]
            return if (value is PhotoBean) {
                1// 照片
            } else {
                0// 日期
            }
        }

        override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
            super.onAttachedToRecyclerView(recyclerView)
            val manager = recyclerView.layoutManager
            if (manager is GridLayoutManager) {
                manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        return when (getItemViewType(position)) {
                            0 -> photoSpanCount
                            else -> 1
                        }
                    }
                }
            }
        }

        private fun findDateIdx(position: Int) {
            if (position in prevDateIdx..nextDateIdx) {
                return
            }

            var i = position// 向前查找
            var j = position// 向后查找

            var flag1 = false;
            var flag2 = false;
            while (true) {
                if (!flag1 && 0 <= i) {
                    if (mPhotoList[i] is String) {
                        flag1 = true
                    } else {
                        --i
                    }
                } else {
                    flag1 = true
                }

                if (!flag2 && j < mPhotoList.size) {
                    if (mPhotoList[j] is String) {
                        flag2 = true
                    } else {
                        ++j
                    }
                } else {
                    flag2 = true
                }

                if (flag1 && flag2) {
                    break
                }
            }

            prevDateIdx = i
            nextDateIdx = j
//            Log.d("ZXF", "prevDateIdx = $i, nextDateIdx = $j")
        }
    }

    inner class PhotoItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
//            super.getItemOffsets(outRect, view, parent, state)

            val space = 0//requireContext().resources.getDimensionPixelOffset(R.dimen.dp_10)

            // 间距处理
            when (view.tag) {
                0 -> {// 日期文本
                    outRect.left =
                        16//requireContext().resources.getDimensionPixelOffset(R.dimen.dp_16)
                    outRect.top =
                        15//requireContext().resources.getDimensionPixelOffset(R.dimen.dp_15)
                    outRect.bottom =
                        8//requireContext().resources.getDimensionPixelOffset(R.dimen.dp_8)
                }
                1 -> {// 图片区第一列
                    outRect.left = 0
                    outRect.bottom = space
                }
                2 -> {// 图片区最后一行
                    outRect.left = space
                    outRect.bottom = 0
                }
                3 -> {// 图片区第一列&最后一行
                    outRect.left = 0
                    outRect.bottom = 0
                }
                else -> {// 图片区非第一列
                    outRect.left = space
                    outRect.bottom = space
                }
            }

            // 最后一行无底边距
            if (photoSpanCount > parent.adapter!!.itemCount - parent.getChildAdapterPosition(view) - 1) {
                outRect.bottom = 0
            }
        }
    }

    override fun bindEvent() {

    }

    fun checkPermission(permissions: Array<String>): Boolean {
        val permissionsList: MutableList<String> = java.util.ArrayList()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsList.add(permission)
            }
        }
        return permissionsList.isEmpty()
    }

    override fun onStop() {
        super.onStop()
        mSelectMap.clear()

    }

    override fun onDestroy() {
        super.onDestroy()
        mSelectMap.clear()
    }

    fun pictureFormatDetection(path: String): Boolean {
        if (path.toLowerCase().endsWith(".jpg") || path.toLowerCase()
                .endsWith(".png") || path.toLowerCase().endsWith(".bmp") ||
            path.toLowerCase().endsWith(".jpeg") || path.toLowerCase()
                .endsWith(".webp") || path.toLowerCase().endsWith(".heic") ||
            path.toLowerCase().endsWith(".cr2") || path.toLowerCase().endsWith(".heif")
        ) {
            return true
        }
        return false
    }


}